package middleware

import (
	"bytes"
	"fmt"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

type MyFomatter struct {
	// 日志前缀
	Prefix string
}

func (m MyFomatter) Format(entry *logrus.Entry) ([]byte, error) {
	// 设置buffer
	var buffer *bytes.Buffer
	if entry.Buffer == nil {
		buffer = &bytes.Buffer{}
	} else {
		buffer = entry.Buffer
	}
	fmt.Fprintf(buffer, "[%s] %s\n", m.Prefix, entry.Message)
	return buffer.Bytes(), nil
}
func LogMiddleWare() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		// 开始时间
		startTime := time.Now()
		path := ctx.Request.URL.Path
		if ctx.Request.URL.RawQuery != "" {
			path = path + "?" + ctx.Request.URL.RawQuery
		}
		ctx.Next()
		timeStr := startTime.Format("2006/01/02 15:04:05")
		clientIP := ctx.ClientIP()
		method := ctx.Request.Method
		statusCode := ctx.Writer.Status()
		endTime := time.Now()
		latency := endTime.Sub(startTime)
		logrus.Infof("%s [%s] %s | %d |  %s |   %s", timeStr, method, clientIP, statusCode, latency, path)
	}
}
